#!/usr/bin/python3

import os
import shutil
import subprocess
import locale
import stat
import glob
import pysed


GOGOPROTOBUF_VERSION = "v1.2.1"
GRPCGATEWAY_VERSION = "v1.9.5"
SYSTEM_ENCODING = locale.getpreferredencoding()
GOPATH = os.getenv("GOPATH")


def execute_command(cmd, working_dir: str = None) -> str:
    c = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=working_dir)
    return c.stdout.read().decode(SYSTEM_ENCODING)


def go_get():
    print("Install gogoprotobuf")
    print(execute_command("go get -u github.com/gogo/protobuf/proto@%s" % GOGOPROTOBUF_VERSION))
    print(execute_command("go get -u github.com/gogo/protobuf/protoc-gen-gogo@%s" % GOGOPROTOBUF_VERSION))
    print(execute_command("go get -u github.com/gogo/protobuf/gogoproto@%s" % GOGOPROTOBUF_VERSION))
    print(execute_command("go get -u github.com/gogo/protobuf/protoc-gen-gofast@%s" % GOGOPROTOBUF_VERSION))
    print(execute_command("go get -u github.com/gogo/protobuf/protoc-gen-gogofast@%s" % GOGOPROTOBUF_VERSION))
    print("Install grpc gateway")
    print(execute_command("go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway@%s" % GRPCGATEWAY_VERSION))
    pass


def copy_dirs(from_file, to_file):
    if not os.path.exists(to_file):  # 如不存在目标目录则创建
        os.makedirs(to_file)
    files = os.listdir(from_file)  # 获取文件夹中文件和目录列表
    for f in files:
        if os.path.isdir(from_file + '/' + f):  # 判断是否是文件夹
            copy_dirs(from_file + '/' + f, to_file + '/' + f)  # 递归调用本函数
        else:
            shutil.copy(from_file + '/' + f, to_file + '/' + f)  # 拷贝文件
            os.chmod(to_file + "/" + f, stat.S_IRWXU+stat.S_IRGRP+stat.S_IXGRP+stat.S_IROTH)


def copy_deps(dest: str):
    copy_dirs("%s/pkg/mod/github.com/gogo/protobuf@%s/protobuf/google" % (GOPATH, GOGOPROTOBUF_VERSION), "%s/google" % dest)
    copy_dirs("%s/pkg/mod/github.com/gogo/protobuf@%s/gogoproto" % (GOPATH, GOGOPROTOBUF_VERSION), "%s/gogoproto" % dest)
    copy_dirs("%s/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@%s/third_party/googleapis/google" % (GOPATH, GRPCGATEWAY_VERSION), "%s/google" % dest)
    pass


def delete_dir(dir):
    for root, dirs, files in os.walk(dir, topdown=False):
        for name in files:
            os.remove(os.path.join(root, name))
        for name in dirs:
            os.rmdir(os.path.join(root, name))


def gen_proto():
    root_dir = os.getcwd()
    print(root_dir)
    dirs = "walpb etcdserverpb snappb raftpb mvccpb leasepb authpb v3lockpb v3electionpb".split(" ")
    for dir in dirs:
        os.chdir(root_dir + "/" + dir)
        current_dir = os.getcwd()
        print("current dir:" + current_dir)
        proto_list = glob.glob("./*.proto")
        for proto in proto_list:
            print(execute_command("protoc --gofast_out=plugins=grpc:. -I. -I.. -I../deps %s" % (proto), working_dir=current_dir))
        pass
    os.chdir(root_dir)
    pass

def sed_proto():
    pb_files = glob.glob("./*/*.pb.go")
    for f in pb_files:
        pysed.replace('authpb "authpb"', 'authpb "go.etcd.io/etcd/proto/authpb"', f)
        pysed.replace('mvccpb "mvccpb"', 'mvccpb "go.etcd.io/etcd/proto/mvccpb"', f)
        pysed.replace('etcdserverpb "etcdserverpb"', 'etcdserverpb "go.etcd.io/etcd/proto/etcdserverpb"', f)
        pysed.replace('_ "google.golang.org/genproto/googleapis/api/annotations"', '', f)
    pass


delete_dir("./deps")
go_get()
copy_deps("./deps")
gen_proto()
sed_proto()